<template>
    <rx-layout :leftStyle="{width:'230px'}">
        <template #left>
            <rx-category-treeeditor
                cat-key="BPM"
                :statisticConfig="statisticConfig"
                read-key="start.read"
                :edit="false"
                @handSelect="handSelect"
                :treeRootList="treeRootList"
                :isBpmClient="isBpmClient"
                :isMyBpm="isMyBpm"
                :async="true">
            </rx-category-treeeditor>
        </template>
        <template #middle>
            <div style="padding: 10px;width: 100%;height: 100%">
                <rx-fit v-model="fitSearch">
                    <template #head>
                        <div style="display: flex;align-items: center;justify-content: space-between;">
                            <div class="table-operator">
                                <a-button type="primary" style="margin-left: 10px;" @click="handBatApprove()">
                                    <template #icon>
                                        <plus-outlined/>
                                    </template>
                                    {{i18n('list.batchApply','批量审批')}}
                                </a-button>
                            </div>
                            <span class="search-btn" @click.stop="searchshow" @mousedown.stop><SearchOutlined/>{{ $ti18('rxList.leachBtn', '过滤') }}</span>
                        </div>
                    </template>
                    <template #search>
                        <a-form layout="vertical">
                            <a-form-item :label="i18n('form.itemTitle','事项标题')">
                                <a-input :placeholder="i18n('form.itemTitle','事项标题','input')"
                                         v-model:value="urlConfig.queryParam['Q_v.SUBJECT__S_LK']"/>
                            </a-form-item>
                            <a-form-item :label="i18n('form.billNo','单号')">
                                <a-input :placeholder="i18n('form.billNo','单号','input')"
                                         v-model:value="urlConfig.queryParam['Q_v.BILL_NO__S_LK']"/>
                            </a-form-item>
                            <a-form-item :label="i18n('form.node','审批环节')">
                                <a-input :placeholder="i18n('form.node','审批环节','input')"
                                         v-model:value="urlConfig.queryParam['Q_v.NAME__S_LK']"/>
                            </a-form-item>
                            <a-form-item :label="i18n('list.taskCreateTime','创建时间') + i18n('list.from','从')" @mousedown.stop>
                                <a-date-picker
                                    :locale="locale"
                                    :getPopupContainer="getPopupContainer"
                                    style="width: 100%"
                                    v-model:value="urlConfig.queryParam['Q_v.CREATE_TIME__D_GE']"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD"
                                    :placeholder="i18n('list.taskCreateTime','请输入任务创建时间','input')"
                                />
                            </a-form-item>
                            <a-form-item :label="i18n('list.to','至')" @mousedown.stop>
                                <a-date-picker
                                    :locale="locale"
                                    :getPopupContainer="getPopupContainer"
                                    style="width: 100%"
                                    :placeholder="i18n('list.taskCreateTime','请输入任务创建时间','input')"
                                    v-model:value="urlConfig.queryParam['Q_v.CREATE_TIME__D_LE']"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD"
                                />
                            </a-form-item>
                        </a-form>
                        <div class="list-search-toolbar">
                            <a-button type="primary" @click="search">
                                <SearchOutlined/>
                                {{ $ti18('rxList.searchBtn', '查询') }}
                            </a-button>
                            <a-button style="margin-left: 4px" @click="resetSearch">
                                <RedoOutlined />
                                {{ $ti18('rxList.resetBtn', '重置') }}
                            </a-button>
                        </div>
                    </template>
                    <template #middle>
                        <rx-grid ref="table"
                                 :hasPage="true"
                                 :urlConfig="urlConfig"
                                 :selectConfig="selectConfig"
                                 url="/api-bpm/bpm/core/bpmTask/myTasks"
                                 field="taskId"
                                 :columns="columns"
                        >
                            <template #status="{row}">
                                <a-tag v-if="row.status == 'UNHANDLE'" color="red">{{i18n('form.wait','待办')}}</a-tag>
                                <a-tag v-else-if="row.status == 'HANDLE'" color="green">{{i18n('form.processing','处理中')}}</a-tag>
                            </template>
                            <template #batchTaskType="{row}">
                                <a-tag v-if="row.batchTaskType == 'BATCH_PARENT'" color="red">{{i18n('taskApply.mergeTasks','任务合并')}}</a-tag>
                                <a-tag v-else color="green">{{i18n('taskApply.publicTasks','普通任务')}}</a-tag>
                            </template>
                            <template #action="{ row }">
                                <RxGridAction :size="2">
                                    <div @click.stop="handleTask(row)">{{i18n('list.handle','办理') }}</div>
                                </RxGridAction>
                            </template>
                        </rx-grid>
                    </template>
                </rx-fit>
            </div>
        </template>
    </rx-layout>
</template>

<script>
import {RxLayout, RxLangInput, RxFit,BaseList,Util} from '@lowcode/jpaas-base-lib';
import FlowUtil from "@/views/modules/bpm/js/FlowUtil.js"
import { App } from '@lowcode/jpaas-share-component';
import TaskBatApprove from "@/views/modules/bpm/ws/TaskBatApprove.vue";
import TaskBatchApprove from "@/views/modules/bpm/ws/TaskBatchApprove.vue";
import userUser from "@/stores/userUser";
import { mapState } from 'pinia';
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import instAndTaskShare from "@/views/modules/column/processOverview/instAndTaskShare.js";
import  rxCategoryTreeeditor from "@/views/modules/column/processOverview/rx-category-treeeditor.vue"


export default {
    name: "MyBpmTaskList",
    components: {RxLayout, RxFit, RxLangInput,rxCategoryTreeeditor,},
    mixins: [BaseList,App,FlowUtil,instAndTaskShare],
    computed:{
        ...mapState(userUser, ['user'])
    },
    data() {
        return {
            locale,
            urlConfig: {
                ajaxType: 'post',
                contentType: 'json',
                queryParam: {},
                dataField: 'result.data',
                totalField: 'result.totalCount'
            },
            selectConfig: {
                type: 'checkbox'
            },
            columns: [
                {
                    title: this.i18n('form.itemTitle', '事项标题'),
                    field: 'subject',
                    minWidth: 200,
                },
                {
                    title: this.i18n('form.billNo', '单号'),
                    field: 'billNo',
                    minWidth: 140,
                },
                {
                    title: this.i18n('form.node', '审批环节'),
                    field: 'name',
                    width: '100px',
                },
                {
                    title: this.i18n('form.status','状态'),
                    field: 'status',
                    width: '100px',
                    slots: { default: 'status' },
                },
                {
                    title: this.i18n('form.taskType','任务类型'),
                    field: 'batchTaskType',
                    slots: { default: 'batchTaskType' },
                    width: 120,
                },
                {
                    title: this.i18n('form.sendTime','发送时间'),
                    field: 'createTime',
                    sortable:true,
                    sortField: 'CREATE_TIME_',
                    width: '160px',
                },
                {
                    title: this.$ti18('rxList.action', '操作'),
                    field: 'action',
                    minWidth: 120,
                    width: '130px',
                    allowCellEdit: false,
                    slots: {default: 'action'},
                },
            ],
            treeRootList:[],
            statisticConfig: {
                type:"static_bpm",
                appIdPrefix:'t.',
                table:"(SELECT t.* FROM BPM_TASK t " +
                    "WHERE ASSIGNEE_ = #{w.curUserId} AND t.TENANT_ID_ = #{w.curTenantId} AND t.STATUS_ != 'COMPLETED' " +
                    "AND t.STATUS_ != 'LOCKED' AND t.STATUS_ != 'PENDING' AND (t.BATCH_TASK_TYPE_ != 'BATCH_SUB' or t.BATCH_TASK_TYPE_ IS NULL ) UNION SELECT t.* " +
                    "FROM BPM_TASK t  " +
                    "LEFT JOIN BPM_TASK_USER u ON t.TASK_ID_ = u.TASK_ID_ " +
                    "WHERE t.ASSIGNEE_ IS NULL AND t.STATUS_ != 'COMPLETED' AND t.STATUS_ != 'LOCKED' AND t.STATUS_ != 'PENDING' " +
                    "AND (u.USER_ID_ = #{w.curUserId} AND t.TENANT_ID_ = #{w.curTenantId} OR u.GROUP_ID_ IN (${w.curUserRoles}))) t",
                tableParams:[{name:"curUserId", type:"string", value:"curUserId", valueType:"context"},
                    {name:"curTenantId", type:"string", value:"curTenantId", valueType:"context"},
                    {name:"curUserRoles", type:"string", value:"curUserRoles", valueType:"context"},
                ],
                field:"t.TREE_ID_",
                whereConf:[]
            },
            readType:"task",
            isBpmClient:false,
            isMyBpm:true,
            batchTaskTypeMap: {
                "BATCH_PARENT": {color: 'red', text: this.i18n('taskApply.mergeTasks','任务合并')},
                "": {color: 'green', text: this.i18n('taskApply.publicTasks','普通任务')}
            },
            broadCastChannel:{}
        }
    },
    beforeUnmount() {
        this.broadCastChannel.close();
    },
    created() {
        let appId=this.curApp.appId;
        if(appId){
            this.urlConfig.queryParam.Q_APP_ID__S_EQ=appId;
        }
        this.initBroadCastChannel();
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"MyBpmTask",key);
        },
        initBroadCastChannel(){
            let self_=this;
            this.broadCastChannel = new BroadcastChannel("broadCastChannel");
            //当待办审批完成关闭时，进行待办列表刷新
            this.broadCastChannel.onmessage=function (event){
                if(event.data && event.data.type=='refreshTask'){
                    self_.search();
                }
            }
        },
        handleTask(record) {
            if("BATCH_PARENT" === record.batchTaskType){
                let self_ = this;
                Util.open(
                    {
                        component: TaskBatchApprove,
                        curVm: this,
                        max:true,
                        title:  this.i18n('taskApply.mergeBatchTasks','任务合并批量审批'),
                        data: {
                            bpmTask: record
                        }
                    },
                    function (action) {
                        self_.refreshGrid();
                    }
                )
                return;
            }
            this.openInst(record.appId,record.instId,record.taskId);
        },
        isContaionBatchTask(rows){
            let task = rows.find(item => {
                return "BATCH_PARENT" === item.batchTaskType;
            });
            return task;
        },
        resetSearch() {
            this.urlConfig.queryParam = {};
            this.queryParam = {};
            let appId=this.curApp.appId;
            if(appId){
                this.urlConfig.queryParam.Q_APP_ID__S_EQ=appId;
                this.queryParam.Q_APP_ID__S_EQ=appId;
            }
            this.$nextTick(() => {
                this.$refs['table'].loadData();
            })
        },
        handBatApprove(){
            var rows=this.$refs.table.getSelectedRows();
            if(!rows || rows.length==0){
                this.$notification.warning({
                    message: this.$ti18('rxMsa.tipsInfo','提示信息'),
                    description:
                        this.i18n('msa.batchSelectTips','请选择需要审批的任务!'),
                });
                return;
            }
            let task = this.isContaionBatchTask(rows);
            if(task && task.taskId){
                this.$notification.warning({
                    message: this.$ti18('rxMsa.tipsInfo','提示信息'),
                    description:this.i18n('msa.batchTips_1','单号【')+task.billNo+this.i18n('msa.batchTips_2','】为合并审批任务，不能进行批量审批!'),
                });
                return;
            }
            let taskAry=rows.map(item=>{
                return item.taskId;
            });
            let self_ = this;
            Util.open(
                {
                    component: TaskBatApprove,
                    curVm: this,
                    max:true,
                    title:  this.i18n('taskApply.pageTitle','任务批量审批'),
                    data: {
                        taskIds: taskAry.join(",")
                    },
                    cancel:function (){
                        self_.refreshGrid();
                    }
                },
                function (action) {
                    self_.refreshGrid();
                }
            )
        },
        getPopupContainer(p){
            return p.parentNode ;
        },
        handSelect(curRow) {
            this.loadDataBySelectTreeNode(curRow);
        },
    },
    watch: {},
}
</script>

<style scoped>

</style>
